import Axios from 'axios';
import {isBrowser} from "../ssr";
import {message} from "antd";

const baseUrl = `${import.meta.env.VITE_APP_SERVER_ENDPOINT}/api/`;
const authKey = `${import.meta.env.VITE_APP_AUTH_KEY || "authKey"}`;

Axios.interceptors.request.use(
    (config) => {
        const isExternal = !!config?.url?.startsWith('http');
        const token = isBrowser ? localStorage.getItem(authKey) : null;
        if (token && !isExternal) {
            config.headers['Authorization'] = `${token}`;
        }
        config.baseURL = baseUrl;
        return config;
    },
    (error) => Promise.reject(error)
);


Axios.interceptors.response.use(response => {
    if (response.data && response.data.errorCode === 99) {
        localStorage.removeItem(authKey)
    }

    if (response.data.message) {
        if (response.data.errorCode == 0) {
            message.success(response.data.message)
        } else {
            message.error(response.data.message)
        }
    }

    return response;
})